//
//  UIView+TYHitExtend.m
//  TYUIKit
//
//  Created by TuyaInc on 2018/11/27.
//

#import "UIView+TYHitExtend.h"

#import <objc/runtime.h>

#import "NSObject+TYUIKitSwizzler.h"

@implementation UIView (TYHitExtend)
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self ty_uikit_swizzleSEL:@selector(pointInside:withEvent:) withSEL:@selector(ty_pointInside:withEvent:)];
    });
}

- (UIEdgeInsets)ty_hitExtend {
    NSValue *value = objc_getAssociatedObject(self, _cmd);
    return value ? [value UIEdgeInsetsValue] : UIEdgeInsetsZero;
}

- (void)setTy_hitExtend:(UIEdgeInsets)ty_hitExtend {
    objc_setAssociatedObject(self, @selector(ty_hitExtend), [NSValue valueWithUIEdgeInsets:ty_hitExtend], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)ty_pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    BOOL result = [self ty_pointInside:point withEvent:event];
    UIEdgeInsets hitExtend = self.ty_hitExtend;
    if (!result
        && !(hitExtend.top == 0 && hitExtend.left == 0 && hitExtend.bottom == 0 && hitExtend.right == 0)
        && !(hitExtend.top == CGFLOAT_MIN && hitExtend.left == CGFLOAT_MIN && hitExtend.bottom == CGFLOAT_MIN && hitExtend.right == CGFLOAT_MIN)) {
        // 全0 / 全CGFloat_Min 则无效
        CGFloat x = -hitExtend.left;
        CGFloat y = -hitExtend.top;
        CGFloat w = self.bounds.size.width + hitExtend.left + hitExtend.right;
        CGFloat h = self.bounds.size.height + hitExtend.top + hitExtend.bottom;
        CGRect rect = CGRectMake(x, y, w, h);
        result = CGRectContainsPoint(rect, point);
    }
    return result;
}

@end
